package com.liuxin.mycontactdemo.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.liuxin.mycontactdemo.R;
import com.liuxin.mycontactdemo.adapter.MyAdapter;
import com.liuxin.mycontactdemo.provider.ContactProvider;
import com.liuxin.mycontactdemo.untils.ThreadUtils;
import com.liuxin.mycontactdemo.untils.ToastUtils;
import com.liuxin.mycontactdemo.vo.Contact;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class ImportContactActivity extends AppCompatActivity {

    @InjectView(R.id.importLv)
    ListView importLv;
    private List<Contact> contactList=new ArrayList<>();
    private MyAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_import_contact);
        ButterKnife.inject(this);
        //给ListView登记ContextMenu
        registerForContextMenu(importLv);
        //读取系统联系人放到contactList
        initData();
        //设置ListView显示数据
        initView();
    }

    private void initView() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                myAdapter=new MyAdapter(ImportContactActivity.this,contactList);
                importLv.setAdapter(myAdapter);
            }
        });
    }

    private void initData() {
        if(ContextCompat.checkSelfPermission(ImportContactActivity.this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(ImportContactActivity.this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else {
            importContact();
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("导入联系人操作");
        menu.add(0,Menu.FIRST,0,"全选");
        menu.add(0,Menu.FIRST+1,1,"全不选");
        menu.add(0,Menu.FIRST+2,2,"导入");
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            case Menu.FIRST:selectAll();break;
            case Menu.FIRST+1:unselectAll();break;
            case Menu.FIRST+2:writeContactToApp();finish();

        }
        return super.onContextItemSelected(item);
    }

    private void writeContactToApp() {
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                int count=0;
                for(Contact contact:contactList){
                    if(contact.isChecked()==true){
                        Cursor cursor=getContentResolver().query(ContactProvider.URI_CONTACT,
                                null,
                                "name=?",
                                new String[]{contact.getName()},
                                null);
                        if (cursor.getCount()==0){
                            ContentValues cv=new ContentValues();
                            cv.put("name",contact.getName());
                            cv.put("phone",contact.getPhone());
                            cv.put("email",contact.getEmail());
                            cv.put("qq","");
                            getContentResolver().insert(ContactProvider.URI_CONTACT,cv);
                            count++;
                        }
                        else{
                            ToastUtils.showToastSafe(ImportContactActivity.this,contact.getName()+"已存在！");
                        }
                        cursor.close();
                    }
                }
                ToastUtils.showToastSafe(ImportContactActivity.this,"已导入！"+count+"个联系人！！！");
            }
        });
    }

    private void unselectAll() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                for(Contact c:contactList){
                    c.setChecked(false);
                }
                initView();
            }
        });
    }

    private void selectAll() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                for(Contact c:contactList){
                    c.setChecked(true);
                }
                initView();
            }
        });
    }

    private void importContact() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                //查找联系人的数据
                Cursor cursor=getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
                //遍历查询结果，获取系统中所有联系人
                while (cursor.moveToNext()){
                    //获取联系人ID
                    String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    //获取联系人名字
                    String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    //使用ContentResolver查找联系人的电话号码
                    Cursor phones=getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                             ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+contactId,
                            null,
                            null);
                    //只获取第一个电话号码
                    String phoneNumber="";
                    if(phones.moveToFirst())
                        phoneNumber=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //关闭phone记录表
                    phones.close();
                    //使用ContentResolver查找联系人的email
                    Cursor emails=getContentResolver().query(
                            ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Email.CONTACT_ID+"="+contactId,
                            null,
                            null
                    );
                    //只获取第一个email
                    String emailAdress="";
                    if (emails.moveToFirst())
                        emailAdress=emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    //关闭emails记录集
                    emails.close();
                    //创建一个联系人对象
                    Contact contact=new Contact(name,phoneNumber,emailAdress,false);
                    //将contact加入到contacts集合中
                    contactList.add(contact);
                }
            }
        });
    }
}
